import axios, { AxiosHeaders, AxiosResponse } from 'axios';
import { AxiosInstance } from 'axios';
import { PUBLIC_PATH } from '@/constant';
import {useTokenStore} from '@/stores/token';

export interface PostResult {
    code: number;
    msg: string;
    data?: {
        [key: string]: any
    };
}

class API {

    private readonly service: AxiosInstance;
    constructor() {
        this.service = axios.create({
            baseURL: PUBLIC_PATH,
            timeout: 50000,
            responseType: 'json',
            headers: { 'Content-Type': 'application/json' },
        });
    }

    async post(url: string | undefined, data: { [p: string]: any } = {}):Promise<PostResult> {
        if(url === undefined){
            let error: PostResult = {
                code: 500,
                msg: 'url is undefined',
            };
            return Promise.reject(error);
        }
        let headers: AxiosHeaders = new AxiosHeaders();
        headers.set('token', useTokenStore().token, true);
        let params = JSON.stringify(data);
        let result = await this.service
            .post<PostResult, AxiosResponse<PostResult>, string>(url, params, {
                headers: headers,
            })
            .then((response) => {
                return response.data;
            })
            .catch((error) => {
                let errorResult: PostResult = {
                    code: error.response.status,
                    msg: error.response.statusText,
                };
                return errorResult;
            });
        if (result) {
            if (Number(result.code) === 200) {
                return Promise.resolve(result);
            } else {
                return Promise.reject(result);
            }
        }
        let error: PostResult = {
            code: 500,
            msg: 'result is empty',
        };
        return Promise.reject(error);
    }
}

const api = new API();
export default api;
